import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:xiecheng_lvyou/dao/travel_dao.dart';
import 'package:xiecheng_lvyou/model/travel_model.dart';
import 'package:xiecheng_lvyou/model/travel_tab_model.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:xiecheng_lvyou/util/navigator_util.dart';
import 'package:xiecheng_lvyou/widget/loading_container.dart';
import 'package:xiecheng_lvyou/widget/webview.dart';

const pageSize = 10;

class TravelTabPage extends StatefulWidget {
  final String? travelUrl;
  final String? groupChannelCode;
  const TravelTabPage({super.key, this.travelUrl, this.groupChannelCode});
  @override
  State<TravelTabPage> createState() => _TravelTabPageState();
}

class _TravelTabPageState extends State<TravelTabPage>
    with AutomaticKeepAliveClientMixin {
  List<TravelItem>? travelItems;
  int pageIndex = 1;
  bool _loading = true;
  final ScrollController _scrollController = ScrollController();

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _loadData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData(loadMore: true);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        body: LoadingContainer(
            isLoading: _loading,
            child: RefreshIndicator(
                onRefresh: _handleRefresh,
                child: MediaQuery.removePadding(
                    removeTop: true,
                    context: context,
                    child: MasonryGridView.count(
                      controller: _scrollController,
                      crossAxisCount: 2,
                      mainAxisSpacing: 4.0,
                      crossAxisSpacing: 4.0,
                      itemCount: travelItems?.length ?? 0,
                      itemBuilder: (BuildContext context, int index) =>
                          _TravelItem(item: travelItems?[index], index: index),
                    )))));
  }

  void _loadData({loadMore = false}) {
    if (loadMore) {
      pageIndex++;
    } else {
      pageIndex = 1;
    }

    TravelDao.fetch(widget.groupChannelCode ?? '', pageIndex, pageSize)
        .then((value) {
      _loading = false;
      setState(() {
        List<TravelItem> items = _filterItems(value.resultList);
        if (travelItems != null) {
          travelItems!.addAll(items);
        } else {
          travelItems = items;
        }
      });
    }).catchError((onError) {
      _loading = false;
    });
  }

  List<TravelItem> _filterItems(List<TravelItem>? resultList) {
    if (resultList == null) {
      return [];
    }
    List<TravelItem> filterItems = [];
    for (var item in resultList) {
      if (item.article != null) {
        //移除article为null的模型
        filterItems.add(item);
      }
    }
    return filterItems;
  }

  Future<Null> _handleRefresh() async {
    _loadData();
    return null;
  }
}

class _TravelItem extends StatelessWidget {
  final int? index;
  final TravelItem? item;

  const _TravelItem({this.index, this.item});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          if (item?.article?.urls != null && item!.article!.urls!.isNotEmpty) {
            print(item!.article!.urls![0].h5Url ?? '');
            NavigatorUtil.push(
                context,
                WebView(
                  url: item!.article!.urls![0].h5Url ?? '',
                  title: '详情',
                ));
          }
        },
        child: Card(
          child: PhysicalModel(
              color: Colors.transparent,
              clipBehavior: Clip.antiAlias,
              borderRadius: BorderRadius.circular(5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _itemImage(),
                  Container(
                    padding: const EdgeInsets.all(4),
                    child: Text(
                      item?.article?.articleTitle ?? '',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style:
                          const TextStyle(fontSize: 14, color: Colors.black87),
                    ),
                  ),
                  _infoTeext()
                ],
              )),
        ));
  }

  _itemImage() {
    return Stack(
      children: [
        Image.network(item?.article?.images?[0].dynamicUrl ?? ''),
        Positioned(
            bottom: 8,
            left: 8,
            child: Container(
              padding: const EdgeInsets.fromLTRB(5, 1, 5, 1),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Row(
                children: [
                  const Padding(
                    padding: EdgeInsets.only(right: 3),
                    child:
                        Icon(Icons.location_on, color: Colors.white, size: 12),
                  ),
                  LimitedBox(
                    maxWidth: 130,
                    child: Text(_poiName(),
                        style: const TextStyle(
                          color: Colors.white,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis),
                  )
                ],
              ),
            ))
      ],
    );
  }

  String _poiName() {
    return item?.article?.pois == null || item!.article!.pois!.isEmpty
        ? '未知'
        : item!.article!.pois![0].poiName ?? '未知';
  }

  _infoTeext() {
    return Container(
      padding: const EdgeInsets.fromLTRB(6, 0, 6, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          PhysicalModel(
            color: Colors.transparent,
            clipBehavior: Clip.antiAlias,
            borderRadius: BorderRadius.circular(12),
            child: Image.network(
              item?.article?.author?.coverImage?.dynamicUrl ?? '',
              width: 24,
              height: 24,
            ),
          ),
          Container(
            padding: const EdgeInsets.all(5),
            width: 90,
            child: Text(
              item?.article?.author?.nickName ?? '',
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontSize: 12),
            ),
          ),
          Row(
            children: [
              const Icon(Icons.thumb_up, size: 14, color: Colors.grey),
              Padding(
                  padding: const EdgeInsets.only(left: 3),
                  child: Text(
                    item?.article?.likeCount?.toString() ?? '',
                    style: const TextStyle(fontSize: 10),
                  ))
            ],
          )
        ],
      ),
    );
  }
}
